package com.nh.controller;

import com.nh.commom.util.PageResult;
import com.nh.commom.util.R;
import com.nh.entity.Books;
import com.nh.service.IBooksService;
import com.nh.VO.BooksVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author QAQ
 * @since 2025-01-13
 */
@RestController
@RequestMapping("/books")
public class BooksController {
    @Autowired
    private IBooksService iBooksService;

    @RequestMapping("/list")
    public R getBookList() {
        return R.ok().data("list", iBooksService.list());
    }

    @GetMapping("/page/{page}/{pageSize}")
    public R findByPage(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize) {
        System.out.println("Request received for findByPage with page: " + page + " and pageSize: " + pageSize);
        PageResult<Books> pr = iBooksService.findByPage(page, pageSize);
        return R.ok().data("pr", pr);
    }

    @PostMapping("/search/{page}/{pageSize}")
    public R search(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize, @RequestBody(required = false) BooksVO vo) {
        PageResult<Books> pr = iBooksService.search(page, pageSize, vo);
        return R.ok().data("pr", pr);
    }

    @PostMapping("/add")
    public R add(@RequestBody Books book) {
        System.out.println("12313123");
        boolean flag = iBooksService.add(book);
        return flag ? R.ok().message("添加书籍成功!") : R.error().message("添加书籍失败!");
    }

    // 修改书籍
    @PutMapping("/update")
    public R update(@RequestBody Books book) {
        boolean flag = iBooksService.updateById(book);
        return flag ? R.ok().message("修改书籍成功!") : R.error().message("修改书籍失败!");
    }

    // 删除书籍（逻辑删除）
    @PutMapping("/delete/{bid}")
    public R delete(@PathVariable("bid") Integer bid) {
        Books book = iBooksService.getById(bid);
        if (book == null) {
            return R.error().message("书籍不存在");
        }
        book.setDeleted(1);
        boolean flag = iBooksService.updateById(book);
        return flag ? R.ok().message("删除书籍成功!") : R.error().message("删除书籍失败!");
    }
}
